package com.yanmaohu.nikita.analyzer;

import com.yanmaohu.nikita.NikitaException;
import com.yanmaohu.nikita.data.expression.NameExpression;
import com.yanmaohu.nikita.data.function.Parameter;
import com.yanmaohu.nikita.data.function.ParameterList;
import com.yanmaohu.nikita.scanner.SourceCode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Bright Lee
 */
public class ParameterAnalyzer {

    private final SourceCode sourceCode;
    private final ParameterList parameterList;

    public ParameterAnalyzer(SourceCode sourceCode, ParameterList parameterList) {
        this.sourceCode = sourceCode;
        this.parameterList = parameterList;
    }

    public void analyze() {
        if (parameterList == null || parameterList.isEmpty()) {
            return;
        }
        Map<String, Parameter> map = new HashMap<>();
        for (int i = 0; i < parameterList.size(); i++) {
            Parameter parameter = parameterList.get(i);
            NameExpression parameterName = parameter.getParameterName();
            String parameterNameString = parameterName.getContent();
            Parameter parameter1 = map.get(parameterNameString);
            if (parameter1 != null) {
                throw new NikitaException(sourceCode, parameterName.getBeginIndex(), parameterName.getEndIndex(), "Duplicate parameter name.");
            }
            map.put(parameterNameString, parameter);
        }
    }

}
